<?php

/*
 * C订单作功能模块
 * 功能：订单
 */

namespace User\Controller;

use Think\C_Controller;

class OrderController extends C_Controller {
    
    /*是否允许重复下单*/
    CONST ALLOW_ONLY = 2;
    CONST NOT_ALLOW_ONLY = 1;

    public function __construct() {
        parent::__construct();
        $this->store_id = (int) $_GET['store_id'];
        if ($this->store_id < 1) {
            throw new \Exception();
        }
        $s = new \Home\Logic\StoreLogic();
        $store = $s->getStore($this->store_id);
        $this->stores = $s->getBlocByStoreId($this->store_id);
        $this->assign('stores',$this->stores);
        $this->assign('logo', $store['logo']);
        $this->assign('store_name', $store['name']);
    }

    public function index() {
        layout('layout2');
        if($_SESSION['client_id']<1){
            redirect("/user/passport/login?store_id=".$this->store_id);
        }
        $o = new \Home\Logic\OrderLogic();
        $orders = $o->getUserOrders(array_keys($this->stores), $_SESSION['client_id'], 0);
        $actions = array();
        $a = new \Home\Logic\ActionLogic();
        foreach ($orders as $k => $v) {
            if (array_key_exists($v['action_id'], $actions)) {
                $action = $actions[$v['action_id']];
            } else {
                $action = $a->getAction($v['action_id']);
                $actions[$v['action_id']] = $action;
            }
            $orders[$k]['end_time'] = date('Y-m-d', $action['end_time']);
            $orders[$k]['action_name'] = $action['action_name'];
            $team = $o->getTeam($v['team_number']);
            $orders[$k]['my'] = $team['user_id'] == $v['client_user'] ? '我开的团' : '我的参团';
            
            //获取商品并兼容老版本
            if($v['create_time']>_UPGRADE_TIME_ && is_numeric($v['type'])){
                $it = new \Home\Logic\ShopitemLogic();
                $item = $it->getItemById($v['type'],$v['store_id'],true);
                $orders[$k]['type'] = $item['name'];
            }
            
            //作弊成团
            if (time() - $v['create_time'] > 172800 && time() <= $v['end_time']) {
                //先写死
                $num = $o->getTeamNum($v['team_number']);
                $orders[$k]['people_num'] = (int) $num['num'] > 2 ? (int) $num['num'] : 3;
                $orders[$k]['_status'] = '成团';
            } else {
                $num = $o->getTeamNum($v['team_number']);
                $orders[$k]['people_num'] = (int) $num['num'];
                $orders[$k]['_status'] = (int) $num['num'] > 2 ? '成团' : '未成团';
            }
        }
        //微信分享
        $api = import('Api2', 'Weixin');
        $api = new \Weixin\Api2();
        $data['jsapi_ticket'] = $api->getTicket(WEIXIN_PAY_APP_ID, WEIXIN_PAY_SECRET);
        $data['noncestr'] = 'fewgasfgadussfeko'; //临时写死
        $data['timestamp'] = time();
        $data['url'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        ksort($data);
        foreach ($data as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $data['sign'] = sha1(substr($str, 0, -1));
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $this->assign('weixin', true);
        }
        $this->assign('data', $data);

        $this->assign('orders', $orders);
        $this->display('order');
    }

    public function append() {
        if($_SESSION['client_id']<1){
            exit;
        }
        $o = new \Home\Logic\OrderLogic();
        $start = (int) $_GET['start'];
        $orders = $o->getUserOrders(array_keys($this->stores), $_SESSION['client_id'], $start);
        if (count($orders) < 1) {
            exit('false');
        }
        $actions = array();
        $a = new \Home\Logic\ActionLogic();
        foreach ($orders as $k => $v) {
            if (array_key_exists($v['action_id'], $actions)) {
                $action = $actions[$v['action_id']];
            } else {
                $action = $a->getAction($v['action_id']);
                $actions[$v['action_id']] = $action;
            }
            $orders[$k]['end_time'] = date('Y-m-d', $action['end_time']);
            $orders[$k]['action_name'] = $action['action_name'];
            $orders[$k]['price'] = $v['price'] / 100;
            $team = $o->getTeam($v['team_number']);
            $orders[$k]['my'] = $team['user_id'] == $v['client_user'] ? '我开的团' : '我的参团';
            $orders[$k]['store_name'] = $this->stores[$v['store_id']];
            
            //获取商品并兼容老版本
            if($v['create_time']>_UPGRADE_TIME_ && is_numeric($v['type'])){
                $it = new \Home\Logic\ShopitemLogic();
                $item = $it->getItemById($v['type'],$v['store_id'],true);
                $orders[$k]['type'] = $item['name'];
            }
 
            //作弊成团
            if (time() - $v['create_time'] > 172800 && time() <= $v['end_time']) {
                //先写死
                $num = $o->getTeamNum($v['team_number']);
                $orders[$k]['people_num'] = (int) $num['num'] > 2 ? (int) $num['num'] : 3;
                $orders[$k]['_status'] = '成团';
            } else {
                $num = $o->getTeamNum($v['team_number']);
                $orders[$k]['people_num'] = (int) $num['num'];
                $orders[$k]['_status'] = (int) $num['num'] > 2 ? '成团' : '未成团';
            }
        }
        exit(json_encode($orders));
    }

    /**
     *  创建订单
     */
    public function createorder() {

        $_GET['mobile'] = trim($_GET['mobile']);
        $team_no = trim($_GET['team_number']);
        if (strlen($team_no) < 1) {
            $team_no = false;
        }
        //验证码
        $code = trim($_GET['code']);
        $mobile = trim($_GET['mobile']);
        $b = new \Home\Logic\BarberLogic();
        if($code != $_SESSION['msg_code'] || $mobile!=$_SESSION['msg_mobile']){
            $this->assign('msg',L('验证码错误'));
            $this->display('msg');
            exit;
        }
        //验证码over
        $action_id = (int) $_GET['aid'];
        $o = new \Home\Logic\OrderLogic();
        $a = new \Home\Logic\ActionLogic();
        $action = $a->getAction($action_id);
        if ($action['id'] < 1 || time() > $action['end_time']) {
            $this->assign('msg',L('活动已结束'));
            $this->display('msg');
            exit;
        }
         // 是否重复下单
        if($action['only']==self::NOT_ALLOW_ONLY ){
            $re = $o->checkOrder($action_id,$_GET['mobile']);
            if($re['id']>0 && $action['model_type']==1 ){
                //拼团
                $this->assign('msg',L('对不起每人只能拼一单哦！！'));
                $this->display('msg');
                exit;
            }elseif($re['id']>0 && $action['model_type']==3){
                //公益
                $this->assign('msg',L('对不起每人只能参与一次公益！！'));
                $this->display('msg');
                exit;
            }
        }

        $s = new \Home\Logic\StoreLogic();
        $store = $s->getStore((int) $_GET['store_id']);
        $u = new \Home\Logic\UserLogic();
        $data['app_id'] = 'nothing';
        $data['store_id'] = $store['id'];
        $data['barber_id'] = (int) $_GET['barber_id'];
        $data['action_id'] = $action_id;
        $team_user['nickname'] = trim($_GET['nickname']);
        $team_user['sex'] = (int) $_GET['sex'] < 0 ? 0 : (int) $_GET['sex'];
        $team_user['headimg'] = trim($_GET['headimg']);
        $team_user['team_number'] = $team_no;
        if ($_SESSION['client_id'] < 1) {
            $b = new \Home\Logic\UserLogic();
            $user = $b->getUserByAccount(trim($_GET['mobile']));
            if ($user['id'] > 0) {
                $user_id = $user['id'];
            } else {
                $user_id = $b->createUser(trim($_GET['mobile']));
            }
        }
        $data['client_user'] = $_SESSION['client_id'] < 1 ? $user_id : $_SESSION['client_id'];
        $data['mobile'] = $_GET['mobile'];
        $data['type'] = $_GET['type'];

        // 区分活动
        if ( $action['model_type'] == 1 || $action['model_type'] == 3 )
        {

            //判断是否为新版拼团，兼容老版
            if(is_numeric($data['type']) && $action['model_type'] == 1)
            {
                $data['type'] = (int)$data['type'];
            }elseif($action['model_type'] == 3){
                $data['type'] = (int)$_GET['type'];
                $data['user_name'] = trim($_GET['user_name']);
            }
                $order_info = $this->buildOrderInfo($data['type'], $data['store_id']);
            
            // 拼团是否免费
            $content = json_decode( $action['content'],true);
            foreach( $content['ids'] as $k=>$v ){
                if( $data['type'] == $k ){
                    $price_ = $v;
                }
            }
            if( $price_>0 ){
                $data['price'] = $price_;  // 需要支付的价格
                $data['status'] = 0;
            }else{
                $data['price'] = 0;        //免费
                $data['status'] = 1;
            }
        }


        //临时over
        if ($_SESSION['s_verify'] == $_GET['verify'] || true) { //解决重复下单
            $_SESSION['s_verify'] = time();
            $this->setSession($_SESSION);
            if($price_>0){
                //if ( strpos( $data['type'], ',') === FALSE ){
                    $re = $o->createOrder($data, $data['client_user'], $team_user,$order_info);
                //}else{
                //  $re = $o->createOrder_multi( $data, $data['client_user'], $team_user,$order_info );
                //}
            }else{
                $re = $o->createOrder($data, $data['client_user'], $team_user,$order_info, true);
            }
        } else {
            $re = $team_no;
        }
        
        //如果免费直接下单，反之进入支付流程
        if( $price_>0 )
        {
            
            // 加一个参数 model_type 用来区分 活动类型
            //redirect(buildUrl('/pay/pay',$data['barber_id']).'&price='.$data['price'].'&order_number='.$re .'&model_type='.$action['model_type'].'&headimg='.$team_user['headimg'].'&nickname='.$team_user['nickname'] );
        }
        else
        {   //拼团
            if($action['model_type'] == 1){
                $orders = $o->getCountByTeamNumber($re);
                $count = count($orders);
                import('MsgCode', 'Msgcode');
                $m = new \Msgcode\MsgCode();
                $a = new \Home\Logic\ActionLogic();
                $action = $a->getAction($orders[0]['action_id']);
                $store = $s->getStore($orders[0]['store_id']);
                if($count == 3 ){  //拼团为3人时发短信给3人
                    foreach($orders as $k=>$v){
                        $mobiles = $v['mobile'];
                        $order_number = $v['order_number'];
                        $_contents = '3&1&'.$store['name'].'&'.$action['action_name'].'&'.$store['tel'].'&'.$order_number;
                        $res = $m->sendMsg_b($mobiles,$_contents,true);
                    }
                }elseif($count>3){  //拼团大于3人时发短信给1人
                    $mobiles = $data['mobile'];
                    $order_number = $orders[0]['order_number'];
                    $_contents = '3&1&'.$store['name'].'&'.$action['action_name'].'&'.$store['tel'].'&'.$order_number;
                    $res = $m->sendMsg_b($mobiles,$_contents,true);
                }
                //$_contents = '3&1&'.$store['name'].'&'.$action['action_name'].'&'.$store['tel'].'&'.$order_number;
                //$res = $m->sendMsg_b($mobiles,$_contents);
                redirect(buildUrl('/user/action/info', $data['barber_id']) . '&team_number=' . $re . '&aid=' . $action_id);
            }
        }

        exit;
    }
    
    public function info(){
        $order_id = (int)$_GET['id'];
        $o = new \Home\Logic\OrderLogic();
        $order = $o->getOrderById($order_id);
        if($order['client_user']!=$_SESSION['client_id']){
            exit;
        }
        $oinfo = new \Home\Logic\OrderinfoLogic();
        $order_info = $oinfo->getOrderInfo($order_id, $order['store_id']);
        
        //微信分享
        $api = import('Api2', 'Weixin');
        $api = new \Weixin\Api2();
        $data['jsapi_ticket'] = $api->getTicket(WEIXIN_PAY_APP_ID, WEIXIN_PAY_SECRET);
        $data['noncestr'] = 'fewgasfgadussfeko'; //临时写死
        $data['timestamp'] = time();
        $data['url'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        ksort($data);
        foreach ($data as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $data['sign'] = sha1(substr($str, 0, -1));
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $this->assign('weixin', true);
        }
        $this->assign('data', $data);
        
        $this->assign('order_info',$order_info);
        $this->display('info');
    }

    public function foo($str) {
        $f = fopen('./public/upload/a.txt', 'a+');
        fwrite($f, $str . "\r\n");
        fclose($f);
    }
    
    public function msg(){
        $this->display('msg');
    }
    
    private function buildOrderInfo($item_id,$store_id){
        $item = new \Home\Logic\ShopitemLogic();
        $_item = $item->getItemById($item_id, $store_id,true);
        if($_item['is_meal_set'] == 1){//如果为套餐商品，则有多条子订单
            $_items = $item->getItemByMealSetId($_item['id'], $store_id,true);
            foreach($_items as $k=>$v){
                //此处添加 临时判断 判断是否有跨店商品
            
            
            
                //over
                $info[$k]['store_id'] = $store_id;
                $info[$k]['item_id'] = $v['id'];
                $info[$k]['item_number'] = $v['item_number'];
                $info[$k]['number'] = $v['number'];
                $info[$k]['count'] = $v['number'];
            }
        }else{//单品
            $info[0]['store_id'] = $store_id;
            $info[0]['item_id'] = $_item['id'];
            $info[0]['item_number'] = $_item['item_number'];
            $info[0]['number'] = 1;
            $info[0]['count'] = 1;        //单品数量固定为1
        }
        return $info;
    }

}
